﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Globalization;

using Revis.VClinicNet.App.Internal;
using Revis.VClinicNet.App.Internal.Dto;
using Revis.VClinicNet.App.Internal.Dto.Validation;
using Revis.VClinicNet.UI.Internal.Mvc.Extensions;
using Revis.VClinicNet.UI.Internal.Mvc.Models;
using Revis.VClinicNet.UI.Internal.Mvc.Infrastructure;
using Revis.VClinicNet.Core.Domain.Credentials;

namespace Revis.VClinicNet.UI.Internal.Mvc.Controllers
{
    public class DoctorController : Infrastructure.ControllerBase
    {
        private IDoctorService _doctorService = null;
        private IVisitService _visitService = null;

        public DoctorController(IDoctorService ids, IVisitService ivs) :
            base("Doctor")
        {
            _doctorService = ids;
            _visitService = ivs;
        }

        /// <summary>
        /// Index  action with list of active doctors
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [HistoryBackLinked]
        [AuthorizeFor(Role = WorkerUserRole.Administrator | WorkerUserRole.Doctor | WorkerUserRole.Recepcionist)]
        public ActionResult IndexR()
        {
            IList<DoctorInfoDto> doctors = _doctorService.ListAllActive() ?? new List<DoctorInfoDto>();
            return View(doctors);
        }

        /// <summary>
        /// Doctor detail action
        /// </summary>
        /// <param name="id">doctor id</param>
        /// <returns></returns>
        [HttpGet]
        [HistoryBackLinked]
        [AuthorizeFor(Role = WorkerUserRole.Administrator | WorkerUserRole.Doctor | WorkerUserRole.Recepcionist)]
        public ActionResult Detail(long id)
        {
            DoctorDetailDto doctor = _doctorService.Find<DoctorDetailDto>(id);
            if (doctor == null) {
                return ErrorView("Nie znaleziono lekarza", "Detail");
            }
            return View(doctor);
        }


        /// <summary>
        /// Return doctor work info + visits in json format
        /// </summary>
        /// <param name="id">doctor id</param>
        /// <param name="date">date to search with</param>
        /// <returns></returns>
        [HttpPost]
        [AuthorizeFor(Role = WorkerUserRole.Administrator | WorkerUserRole.Doctor | WorkerUserRole.Recepcionist)]
        public JsonResult JsonWorkInfo(long id, string date)
        {
            DateTime parsedDate;
            JsonWorkInfoModel model = null;
            bool isDateParseSuccess = DateTime.TryParse(date, out parsedDate);
            if (isDateParseSuccess == true) {
                DoctorWorkInfoDto workInfo = _doctorService.FindWorkInfo(id, parsedDate);
                model = new JsonWorkInfoModel(workInfo);
            }
            return Json(model ?? new JsonWorkInfoModel(), JsonRequestBehavior.AllowGet);
        }
    }
}
